package com.zhouxiaoge.springbatch_rest;

import org.springframework.batch.core.*;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 周小哥
 * @date 2021年08月02日 11点12分
 */

@RestController
public class JobLaunchingController {

    public final JobLauncher jobLauncher;

    public final ApplicationContext applicationContext;

    @Autowired
    public JobExplorer jobExplorer;

    public JobLaunchingController(JobLauncher jobLauncher, ApplicationContext applicationContext) {
        this.jobLauncher = jobLauncher;
        this.applicationContext = applicationContext;
    }

    @PostMapping("/run")
    public ExitStatus runJob(@RequestBody JobLaunchRequest jobLaunchRequest) throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
        Job job = this.applicationContext.getBean(jobLaunchRequest.getName(), Job.class);
        JobParameters jobParameters = new JobParametersBuilder(jobLaunchRequest.getJobParameters(), this.jobExplorer).getNextJobParameters(job).toJobParameters();
        return this.jobLauncher.run(job, jobParameters).getExitStatus();
    }
}
